package Utils;

import io.restassured.response.Response;
import org.apache.log4j.Logger;
import org.testng.Reporter;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * json断言类
 * 传入预期值和实际值进行对比
 * 把从表格的值以分号才分开，分成数组
 * 遍历数组，把值以等号拆分开，分成json path 和预期值，储存成map形式
 * <p>
 * 1、生成map
 * 2、获取实际值
 * 3、断言
 * <p>
 * 遍历map使用json path来获取实际值，和预期值对比
 * Created by 80736 on 2017/7/1.
 */

public class JsonUtil {
    private Response response;
    private String expect;
    private String jsonpath;
    private Logger logger = MyLogs.getLogger();

    public JsonUtil(Response response, String expect) {
        this.response = response;
        this.expect = expect;
    }

    public JsonUtil(String jsonpath) {
        this.jsonpath = jsonpath;
    }

    /**
     * 获取map形式的excel数据
     * jsonpath：预期值
     *
     * @return
     */
    public Map<String, String> getPathMap() {
        Map<String, String> json = new HashMap<>();
        String[] str = null;
        if (expect != null) {
            if (expect.contains(";")) {
                str = expect.split(";");
            } else {
                str = new String[1];
                str[0] = expect;
            }
        }

        for (int i = 0; i < str.length; i++) {
            if (str[i].contains("=")) {
                String[] result = str[i].split("=", 2);
                json.put(result[0], result[1]);
            }

        }

        return json;
    }


    /**
     * 判断预期和实际值是否相符
     *
     * @param json
     * @return
     */
    public boolean assertValue(Map<String, String> json) {
        for (String key : json.keySet()) {
            String exceptedValue = json.get(key);
            String jsonResult = getActualValue(key);
            logger.info("数据校验>>预期值为：" + exceptedValue + "-----实际值为：" + jsonResult);
            if (!Objects.equals(jsonResult, exceptedValue)) {
                Reporter.log("数据校验>>预期值为：" + exceptedValue + "-----实际值为：" + jsonResult);
            } else {
                Reporter.log("测试通过！");
            }
            return Objects.equals(jsonResult, exceptedValue);

        }
        return false;
    }


    /**
     * 获取接口返回的实际值
     *
     * @param value
     * @return
     */
    private String getActualValue(String value) {

        String result = response.getBody().jsonPath().getString(value);

        logger.debug("接口返回的json数据中，实际值为：" + result);
        return result;

    }

    /**
     * 根据jsonpath规则，获取响应对象的值
     *
     * @param response
     * @return
     */
    public String getJsonData(Response response) {
        return response.getBody().jsonPath().getString(jsonpath);
    }
}
